import json
from flask import current_app
from openai import OpenAI

import logging
from common import Result
import requests
from .. import AiAdapter, AiQuery, AiQueryResult
from config.config import AppConfig
from api.home.service import HomeService

#
##
# https://platform.moonshot.cn/docs/api/chat#%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B
#
#

_MODEL_VERSION = "moonshot-v1-8k"

LOGGER = logging.getLogger(__name__)


class Kimi(AiAdapter):

    def query(self, query: AiQuery) -> AiQueryResult:

        try:
            res: Result = HomeService().getSetting()
            API_KEY = res.data['apikeyKimi']
            LOGGER.info(f"kimi读取到的key是: {API_KEY}")
            if not res.is_success():
                return AiQueryResult(isValid=False, errMessage="请在配置页面，填写配置")
        except Exception as e:
            LOGGER.exception(e)
            return AiQueryResult(
                isValid=False, errMessage=f"请在配置页面，填写配置:{str(e)}"
            )

        try:
            LOGGER.info(f"发出请求：{query.userMessage}")

            url = "https://api.moonshot.cn/v1/chat/completions"
            headers = {
                "Authorization": f"Bearer {API_KEY}",
                "Content-Type": "application/json",
            }
            payload = {
                "model": _MODEL_VERSION,
                "messages": [{"role": "user", "content": query.userMessage}],
            }

            requests.packages.urllib3.disable_warnings()
            r = requests.post(url=url, headers=headers, json=payload, verify=False)
            LOGGER.info(f"接口返回code:{r.status_code} body:{r.text}")
            if r.status_code == 200:
                jsonResponse = json.loads(r.text)
                return AiQueryResult(
                    text=jsonResponse["choices"][0]["message"]["content"],
                    totalToken=jsonResponse["usage"]["total_tokens"],
                )
            else:
                return AiQueryResult(isValid=False, errMessage=r.text)
        except Exception as e:
            LOGGER.exception(e)
            return AiQueryResult(isValid=False, errMessage=str(e))
